<template>
  <div class="login">
    <div class="box">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item>
          <div style="text-align: center">
            <img src="../../assets/common/login-logo.png" alt="">
          </div>
        </el-form-item>
        <el-form-item prop="mobile">
          <el-input
            v-model="form.mobile"
            prefix-icon="el-icon-user-solid"
            @keyup.enter.native="submit"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            prefix-icon="el-icon-lock"
            type="password"
            @keyup.enter.native="submit"
          />
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%" @click="submit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      form: {
        mobile: '13800000002',
        password: '123456'
      },
      rules: {
        mobile: [
          { required: true, message: '必填项', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              const reg =
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的手机号'))
              }
            },
            trigger: 'change'
          }
        ],
        password: [
          { required: true, message: '必填项', trigger: 'change' },
          {
            min: 6,
            max: 12,
            messgae: '请输入6-12位密码',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    // 点击登录 预校验表单 发送请求 input框回车也调用此函数
    // element-ui 的input事件为change 但是如果要用原生的加上修饰符native
    submit() {
      this.$refs.form.validate(async(res) => {
        if (res) {
          // 将后台显示的响应失败 统一写在拦截器
          // const data = await sysLogin(this.form)
          // console.log(data)
          // this.$message.success('验证通过')

          // 方式2:直接触发仓库中的异步请求
          await this.$store.dispatch('user/toLogin', this.form)
          // 登录成功后跳转到首页  此时需要注意执行机制问题,直接写跳转会导致先执行跳转再发起请求.解决:加上async 与await
          // this.$router.push('/')
          // 如果有携带参数或者回跳地址,则登陆成功时 直接跳转到对应地址
          const _redirect = this.$route.query.redirect || '/'
          this.$router.push(_redirect)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.login {
  height: 100%;
  background: url('../../assets/common/login.jpg') no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  .box {
    width: 450px;
    .el-button {
      background-color: #407ffe;
      color: #fff;
      border-width: 0;
    }
  }
}
</style>
